package com.gis.controller;

import com.gis.dto.OilspillDTO;
import com.gis.dto.RedtideDTO;
import com.gis.entity.StationData;
import com.gis.exception.CustomException;
import com.gis.result.ResponseResult;
import com.gis.service.ReportExportService;
import com.gis.service.StationDataService;
import com.gis.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.*;

import static com.gis.maps.commonMap.getSeason;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/report")
@CrossOrigin(origins = "*")
@Tag(name = "报告导出")
public class ReportExportController {
    final private ReportExportService reportExportService;
    final private StationDataService stationDataService;

    /**
     * 返回报告PDF
     * @param response
     * @param year
     * @param season
     */
    @Operation(summary = "所有站点评价及预警报告")
    @Parameters({
            @Parameter(name = "type", description = "类型（水质、沉积物、生物质量、赤潮、溢油）", required = true),
            @Parameter(name = "year", description = "年", required = true),
            @Parameter(name = "season", description = "季度", required = true),
            @Parameter(name = "screenshot", description = "图片")
    })
    @PostMapping("/getReport")
    public void getReport(@RequestParam String type,
                          @RequestParam int year,
                          @RequestParam String season,
                          @RequestParam(required = false) String screenshot,
                          HttpServletResponse response) {
        // 封装返回的文件
        try {
            // 1. 调用 service 生成 PDF 并获取输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (type.equals("水质")) {
                reportExportService.generateWaterQualityReport(baos, year, season, screenshot);
            } else if (type.equals("沉积物")) {
                reportExportService.generateSedimentReport(baos, year, season, screenshot);
            } else if (type.equals("生物质量")) {
                reportExportService.generateBiologyReport(baos, year, season, screenshot);
            } else if (type.equals("赤潮")) {
                reportExportService.generateRedtideReport(baos, year, season, screenshot);
            } else if (type.equals("溢油")) {
                reportExportService.generateOilspillReport(baos, year, season, screenshot);
            } else {
                throw new CustomException("无效类型");
            }

            // 2. 设置响应头
            response.setContentType("application/pdf");
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Expires", "0");

            // 3. 设置文件名
            String filename = String.format("%s报告_%d年%s.pdf", type, year, season);
            String encodedFilename = URLEncoder.encode(filename, "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFilename);

            // 4. 写入输出流
            response.setContentLength(baos.size());
            baos.writeTo(response.getOutputStream());
            response.flushBuffer();

        } catch (Exception e) {
            log.error("PDF生成失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw new CustomException("PDF生成失败");
        }
    }


    /**
     * 返回水质报告表格值
     * @param year
     * @param season
     * @return
     */
    @Operation(summary = "所有站点评价预警")
    @Parameters({
            @Parameter(name = "type", description = "类型（水质、沉积物、生物质量、赤潮、溢油）", required = true),
            @Parameter(name = "year", description = "年", required = true),
            @Parameter(name = "season", description = "季度", required = true),
    })
    @GetMapping("/getLevel")
    public ResponseResult<List<ReportVO>> getLevel(String type, int year, String season) {
        List<ReportVO> reportVOS = new ArrayList<>();
        if(type.equals("水质")){
            List<WaterQualityReportVO> waterQuality = reportExportService.getWaterQuality(year, season);
            for (WaterQualityReportVO waterQualityReportVO : waterQuality){
                ReportVO reportVO = new ReportVO();
                BeanUtils.copyProperties(waterQualityReportVO, reportVO);
                reportVOS.add(reportVO);
            }
            return ResponseResult.success(reportVOS);
        } else if (type.equals("沉积物")) {
            List<SedimentReportVO> sedimentQuality = reportExportService.getSedimentQuality(year, season);
            for (SedimentReportVO sedimentReportVO : sedimentQuality){
                ReportVO reportVO = new ReportVO();
                BeanUtils.copyProperties(sedimentReportVO, reportVO);
                reportVOS.add(reportVO);
            }
            return ResponseResult.success(reportVOS);
        } else if (type.equals("生物质量")) {
            List<BiologyReportVO> sedimentReportVOS = reportExportService.getBiologyQuality(year, season);
            for (BiologyReportVO biologyReportVO : sedimentReportVOS){
                ReportVO reportVO = new ReportVO();
                BeanUtils.copyProperties(biologyReportVO, reportVO);
                reportVOS.add(reportVO);
            }
            return ResponseResult.success(reportVOS);
        } if(type.equals("赤潮")){
            List<RedtideDTO> redtideDTOS = reportExportService.getRedtide(year, getSeason(season));
            for (RedtideDTO redtideDTO : redtideDTOS){
                ReportVO reportVO = new ReportVO();
                StationData stationData = stationDataService.getById(redtideDTO.getStationId());
                BeanUtils.copyProperties(stationData,reportVO);
                reportVO.setLevel(redtideDTO.getResult().getName());
                reportVOS.add(reportVO);
            }
            return ResponseResult.success(reportVOS);
        } else if (type.equals("溢油")) {
            List<OilspillDTO> oilspillVOS = reportExportService.getOilspill(year, getSeason(season));
            for (OilspillDTO oilspillDTO : oilspillVOS){
                ReportVO reportVO = new ReportVO();
                StationData stationData = stationDataService.getById(oilspillDTO.getStationId());
                BeanUtils.copyProperties(stationData,reportVO);
                reportVO.setLevel(oilspillDTO.getResult().getName());
                reportVOS.add(reportVO);
            }
            return ResponseResult.success(reportVOS);
        }else {
            return ResponseResult.fail("请求参数错误");
        }

    }


    @Operation(summary = "详细水质评价")
    /**
     * 返回水质报告表格值
     * @param year
     * @param season
     * @return
     */
    @GetMapping("/waterQuality")
    public ResponseResult<List<WaterQualityReportVO>> getWaterQuality(int year, String season) {
        List<WaterQualityReportVO> waterQuality = reportExportService.getWaterQuality(year, season);
        return ResponseResult.success(waterQuality);
    }


    /**
     * 沉积物报告表格
     * @param year
     * @param season
     * @return
     */
    @Operation(summary = "详细沉积物评价")
    @GetMapping("/sedimentQuality")
    public ResponseResult<List<SedimentReportVO>> getSedimentQuality(int year, String season) {
        List<SedimentReportVO> sedimentQuality = reportExportService.getSedimentQuality(year, season);
        return ResponseResult.success(sedimentQuality);
    }


    /**
     * 生物质量报告表格
     * @param year
     * @param season
     * @return
     */
    @Operation(summary = "详细生物质量评价")
    @GetMapping("/biologyQuality")
    public ResponseResult<List<BiologyReportVO>> getBiologyQuality(int year, String season) {
        List<BiologyReportVO> sedimentReportVOS = reportExportService.getBiologyQuality(year, season);
        return ResponseResult.success(sedimentReportVOS);
    }
}
